﻿using MediatR;
using SmartCity.ProcessEngine.Api.Read.Application.Command.Node;
using SmartCity.ProcessEngine.Api.Read.Dtos;
using SmartCity.ProcessEngine.Domain.Entities;
using SmartCity.ProcessEngine.ErrorCode;
using SmartCity.ProcessEngine.Infrastructure.Extention;
using SmartCity.ProcessEngine.Infrastructure.Interface;

namespace SmartCity.ProcessEngine.Api.Read.Application.CommandHandler.Node
{
    public class GetNodeHandler : IRequestHandler<GetNodeCommand, ApiPaging<NodeDTO>>
    {
        private readonly IBaseRepository<NodeModel> nodeRepo;
        private readonly ILogger<GetNodeHandler> logger;

        public GetNodeHandler(IBaseRepository<NodeModel> nodeRepo,ILogger<GetNodeHandler> logger)
        {
            this.nodeRepo = nodeRepo;
            this.logger = logger;
        }
        public async Task<ApiPaging<NodeDTO>> Handle(GetNodeCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<NodeDTO> res = new ApiPaging<NodeDTO>();
            var nodes = nodeRepo.GetAll().Where(x => x.IsDeleted == false&&x.FormId==request.FormId);

            try
            {
                if (request.NodeCode.IsNotNull())
                {
                    nodes = nodes.Where(x => x.NodeCode.Contains(request.NodeCode));
                }

                if (request.NodeName.IsNotNull())
                {
                    nodes = nodes.Where(x => x.NodeName.Contains(request.NodeName));
                }

                var linq = from node in nodes
                           select new NodeDTO { NodeName = node.NodeName, Id = node.Id, NodeCode = node.NodeCode, NodeDes = node.NodeDes };

               
                res.Msg = "获取节点分页列表成功!";
                res.TotalCount = linq.Count();
                res.PageDatas = linq.OrderByDescending(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                res.Code = ApiEnum.Success;
            }
            catch (Exception e)
            {
                logger.LogError($"查询节点分页列表时发生异常,{e.Message}");       //最可能发生发生的异常: 数据库连接中断  
            }

            return res;

        }
    }
}
